<?php
/**
 * @author Zwc
 * Created On 2022/5/27 20:59
 */

namespace app\auth\service;


use app\common\models\OperateLogModel;

class OperateLogService extends BaseService
{
	protected $model;
	public function __construct()
	{
		parent::__construct();
		$this->model = new OperateLogModel();

	}

	/**
	 * 获取数据
	 */
	public function getData($params) {
		$this->addLog($this->userId,$_SERVER['REQUEST_URI'],'查询操作日志',$params);
		$condition = $this->getCondition($params);
		$count = $this->model->where($condition)->count();
		$data = $this->model->where($condition)->page($params['page'],$params['limit'])
			->order('id desc')->select();
		$adminIdList = [];
		foreach ($data as $val) {
			$adminIdList[] = $val['user_id'];
		}
		$adminService = new AdminUserService();
		$adminUserData = $adminService->getAdminUserByList($adminIdList);
		foreach ($data as &$val) {
			$val['adminName'] = isset($adminUserData[$val['user_id']]) ? $adminUserData[$val['user_id']]['user_name'] : '';
		}
		return ['code' => 0,'msg' => '获取数据成功','data' => $data,'count' => $count];
	}

	/**
	 * 添加操作日志
	 * @param $userId
	 * @param $url
	 * @param $title
	 * @param $params
	 */
	public function addLog($userId,$url,$title,$params) {
		$data = [
			'user_id' => $userId,
			'url' => $url,
			'title' => $title,
			'ip' => $_SERVER['SERVER_ADDR'],
			'params' => json_encode($params,JSON_UNESCAPED_UNICODE)
		];
		$this->model->insert($data);
	}

	/**
	 * 获取查询条件
	 */
	private function getCondition($params) {
		$condition = $this->initCondition();
		if(!empty($params['userId'])) {
			$condition[] = ['user_id','=', $params['userId']];
		}

		if(!empty($params['startTime'])) {
			$condition[] = ['create_time','>=', $params['startTime']];
		}

		if(!empty($params['endTime'])) {
			$condition[] = ['create_time', '<=', $params['endTime']];
		}

		if(!empty($params['keyword'])) {
			$condition[] = ['title','like' , '%'.$params['keyword'].'%'];
		}

		return $condition;
	}

}